﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BitPortal.Models;
using BitPortal.Utils;

namespace BitPortal.Business
{
    public static partial class KeyWordBLL
    {
        /// <summary>
        /// Cap nhat keyword vao database
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static int Save(this Keyword keyword)
        {
            ExtendedBitPortalEntities eBitEnt = new ExtendedBitPortalEntities();
            Keyword k = eBitEnt.Keywords.SingleOrDefault(ent => ent.KeyName == keyword.KeyName);
            if (k != null)
            {
                k.ResultCount = keyword.ResultCount;
                k.SearchCount++;
                k.DatetimeLastSearch = DateTime.Now;
            }
            else
            {
                keyword.LanguageCode = BitContext.Current.Lang.LanguageCode;
                keyword.DatetimeFirstSearch = keyword.DatetimeLastSearch = DateTime.Now;
                keyword.SearchCount = 1;
                keyword.SortOrder = 0;
                keyword.NoneUnicodeValue = keyword.KeyName.ToStringRejexMarks();
                
                eBitEnt.Keywords.AddObject(keyword);
            }
            return eBitEnt.SaveChanges();
        }

        /// <summary>
        /// Lay ra nhung tu khoa gan voi tu khoa dua vao
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static List<string> ListSameKeyWord(string keyword)
        {
            return (from ent in (new ExtendedBitPortalEntities()).Keywords
                    where ent.NoneUnicodeValue.Contains(keyword)
                    orderby ent.SortOrder descending, ent.SearchCount descending, ent.ResultCount descending
                    select ent.KeyName).ToList();
        }

    }
}